<template>
  <div class="bigbox">
    <div class="common-header">
      <div style="cursor: pointer" @click="goback()">
        <i class="vxe-icon-arrow-left" style="vertical-align: middle"></i
        ><span style="vertical-align: middle">返回</span>
      </div>
      <div>
        <el-button v-if="!isCheck" type="primary" size="small" @click="save">保存</el-button>
      </div>
    </div>
    <div class="content_box">
      <el-scrollbar ref="scrollMenuRef" style="height: 100%">
        <div>
          <div class="info">
            <p class="title"><span class="titleName">基础信息</span></p>
            <vxe-form class="content" :data="form">
              <vxe-form-item title="项目编号" field="projectCode" :item-render="{}">
                <template #default="{ data }">
                  <vxe-input
                    v-model="data.projectCode"
                    class="normal"
                    disabled
                    placeholder="项目编号"
                    clearable
                  ></vxe-input>
                </template>
              </vxe-form-item>
              <vxe-form-item title="项目全称" field="projectName" :item-render="{}">
                <template #default="{ data }">
                  <vxe-input
                    v-model="data.projectName"
                    class="normal"
                    placeholder="请输入项目全称"
                    suffix-icon="vxe-icon-menu"
                    readonly
                    :disabled="!!form.id"
                    @click="openProject"
                    @change="fetchInfoExport"
                  ></vxe-input>
                </template>
              </vxe-form-item>
              <vxe-form-item title="月份" field="fillMonth" :item-render="{}">
                <template #default="{ data }">
                  <vxe-input
                    v-model="data.fillMonth"
                    placeholder="月份"
                    class="date"
                    type="month"
                    :disabled="!!form.id"
                    valueFormat="yyyy-MM"
                    @change="fetchInfoExport"
                  ></vxe-input>
                </template>
              </vxe-form-item>
              <vxe-form-item v-if="isCheck" title="文件" field="" :item-render="{}">
                <template #default="{ data }">
                  <div v-show="fileUrl" class="fileContent">
                    <img class="img" src="../../assets/images/icon_excel.png" alt="" />
                    <span class="filename">{{ form.fileName }}</span>
                    <p class="downloadIcon">
                      <i class="vxe-icon-download" style="cursor: pointer" @click="download"></i>
                    </p>
                  </div>
                </template>
              </vxe-form-item>
            </vxe-form>
          </div>
          <div class="info" v-if="!isCheck">
            <p class="title">
              <span class="titleName">运营信息表上传</span>
            </p>
            <div class="content">
              <vxe-button class="download" size="small" icon="vxe-icon-download" @click="exp">下载模板</vxe-button>
              <div class="uploadFile">
                <vxe-button class="upload" status="primary" size="small" icon="vxe-icon-upload" @click="imp"
                  >点击上传</vxe-button
                >
                <span class="uploadTip">(单个文件最大500MB)</span>
                <div v-show="fileUrl" class="fileContent">
                  <img class="img" src="../../assets/images/icon_excel.png" alt="" />
                  <span class="filename">{{ form.fileName }}</span>
                  <p class="downloadIcon">
                    <i class="vxe-icon-download" style="cursor: pointer" @click="download"></i>
                  </p>
                </div>
              </div>
            </div>
          </div>
          <div class="info" v-show="tableData.length > 0">
            <p v-sticky class="title"><span class="titleName">运营信息表</span></p>
            <div class="content clearfix">
              <div v-sticky="{ stickyTop: 38, zIndex: 8 }" class="leftContent">
                <el-scrollbar style="height: calc(100vh - 125px)">
                  <ul class="menuList">
                    <li
                      v-for="(item, i) in tableData"
                      :key="item.name"
                      :id="item.name"
                      :class="{ active: i == curIndex }"
                      @click="sel(i)"
                    >
                      {{ item.name }}
                    </li>
                  </ul>
                </el-scrollbar>
              </div>
              <div class="rightContent">
                <div v-for="(item, i) in showTableData" :key="item.id" class="clearfix menuContent scrollItem" :id="i">
                  <p class="small-title">
                    {{ item.name }}
                  </p>
                  <vxe-table :show-header="false" :data="item.children" border="none" class="rightContent_box">
                    <vxe-column field="column1" title="">
                      <template #default="{ row }">
                        <p class="name">{{ row.column1?.name }}</p>
                        <p class="value">{{ row.column1?.value }}</p>
                      </template>
                    </vxe-column>
                    <vxe-column field="column2" title="">
                      <template #default="{ row }">
                        <p class="name">{{ row.column2?.name }}</p>
                        <p class="value">{{ row.column2?.value }}</p>
                      </template>
                    </vxe-column>
                    <vxe-column field="column3" title="">
                      <template #default="{ row }">
                        <p class="name">{{ row.column3?.name }}</p>
                        <p class="value">{{ row.column3?.value }}</p>
                      </template>
                    </vxe-column>
                    <vxe-column field="column4" title="" show-overflow>
                      <template #default="{ row }">
                        <p class="name">{{ row.column4?.name }}</p>
                        <p class="value">{{ row.column4?.value }}</p>
                      </template>
                    </vxe-column>
                  </vxe-table>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>
    <!-- 选择项目 -->
    <Project
      ref="table"
      :dialogVisible="ProjectVisible"
      :tableData="ProjectData"
      :showSelection="true"
      :maxHeight="400"
      showPage
      :total="Projectotal"
      :pageSize="ProjectParams.pageSize"
      :currentPage="ProjectParams.page"
      :tableColumn="tableColumn"
      @changePage="changePage"
      @sizeChange="sizeChange"
      @refresh="refreshPro"
      @searchPro="searchProject"
      @changeSelection="handleSelect"
      @rowClick="rowClick"
      @submit="submitProject3"
      @hideDialog="closeProject3"
    ></Project>
  </div>
</template>
<script>
import * as ExcelJS from 'exceljs';
import { v4 as uuidv4 } from 'uuid';
import util from '@/util/util';
import VXETable from 'vxe-table';
import Project from '/@/components/Project/index.vue';
import VueSticky from 'vue-sticky';
export default {
  components: { Project },
  directives: {
    sticky: VueSticky,
  },
  data() {
    return {
      space: '&nbsp;',
      ProjectVisible: false,
      curIndex: '',
      statuss: [
        { label: '禁用', value: '0' },
        { label: '启用', value: '1' },
      ],
      result: [
        {
          name: '产值',
          value: null,
          startColumn: 1,
          endColumn: 1,
          options: null,
          children: [
            {
              name: '累计产值1',
              value: '在建',
              lineNumber: 2,
              startColumn: 2,
              endColumn: 9,
              options: ['在建', '停工'],
              children: null,
              projectRecordId: 102,
              field: '累计产值1',
              fieldValue: 1,
              month: '2023-05',
            },
            {
              name: '累计产值2',
              value: '在建',
              lineNumber: 3,
              startColumn: 2,
              endColumn: 3,
              options: ['在建', '停工'],
              children: null,
              projectRecordId: 102,
              field: '累计产值2',
              fieldValue: 2,
              month: '2023-05',
            },
            {
              name: '累计产值3',
              value: '在建',
              lineNumber: 3,
              startColumn: 4,
              endColumn: 5,
              options: ['在建', '停工'],
              children: null,
              projectRecordId: 102,
              field: '累计产值3',
              fieldValue: 3,
              month: '2023-05',
            },
          ],
          projectRecordId: 102,
          field: '产值',
          month: '2023-05',
        },
        {
          name: '签证',
          value: null,
          startColumn: null,
          endColumn: null,
          options: ['在建', '停工'],
          children: [
            {
              name: '签证-1',
              value: '在建',
              lineNumber: 5,
              startColumn: 2,
              endColumn: 9,
              options: ['在建', '停工'],
              children: null,
              projectRecordId: 102,
              field: '签证-1',
              fieldValue: 4,
              month: '2023-05',
            },
          ],
          projectRecordId: 102,
          field: '签证',
          month: '2023-05',
        },
        {
          name: '地产',
          value: null,
          lineNumber: 9,
          startColumn: 2,
          endColumn: 9,
          options: null,
          children: [
            {
              name: '地产-1',
              value: '在建',
              lineNumber: 9,
              startColumn: 2,
              endColumn: 9,
              options: ['在建', '停工'],
              children: null,
              projectRecordId: 102,
              field: '地产-1',
              fieldValue: 5,
              month: '2023-05',
            },
          ],
          projectRecordId: 102,
          field: '地产',
          month: '2023-05',
        },
        {
          name: '测试',
          value: null,
          options: null,
          children: [
            {
              name: '测试-1',
              value: '在建',
              lineNumber: 15,
              startColumn: 2,
              endColumn: 5,
              options: ['在建', '停工'],
              children: null,
              projectRecordId: 102,
              field: '测试-1',
              fieldValue: 5,
              month: '2023-05',
            },
            {
              name: '测试-2',
              value: '在建',
              lineNumber: 15,
              startColumn: 6,
              endColumn: 9,
              options: ['在建', '停工'],
              children: null,
              projectRecordId: 102,
              field: '测试-2',
              fieldValue: 5,
              month: '2023-05',
            },
          ],
          projectRecordId: 102,
          field: '地产',
          month: '2023-05',
        },
      ],
      tableData: [],
      newTable: [],
      mergeCells: [],
      tableImport: {
        // 自定义类型
        types: ['xlsx'],
      },
      tableExport: {
        // 默认选中类型
        type: 'xlsx',
        // 自定义类型
        types: ['xlsx', 'csv', 'html', 'xml', 'txt'],
      },
      atozStr: 'ABCDEFGHI',
      atozArr: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'],
      column: 4,
      selections: [],
      selection: {},
      // id: 102,
      // month: '2023-05',
      // businessId: this.$route.query.id,
      form: {
        id: '',
        projectCode: '',
        projectName: '',
        orgCode: '',
        orgName: '',
        fileId: '',
        fileName: '',
        fillMonth: '',
      },
      fileUrl: null,
      ProjectData: [],
      //项目请求
      ProjectParams: {
        projectName: null,
        projectId: null,
        page: 1,
        pageSize: 10,
      },
      projectList: [],
      Projectotal: 0,
      tableColumn: {
        projectCode: {
          label: '项目编码',
        },
        projectId: {
          label: '项目id',
        },
        projectName: {
          label: '项目名称',
        },
        orgName: {
          label: '所属组织',
        },
      },
      userInfo: null,
      templateData: [],
      isCheck: false,
    };
  },
  computed: {
    showTableData() {
      const result = this.tableData.map((item) => {
        let prevLineNumber = null;
        const newItem = { ...item };
        newItem.children = item.children?.reduce((prev, cur) => {
          if (prevLineNumber == cur.lineNumber) {
            let last = prev[prev.length - 1];
            last[`column${cur.startColumn / 2}`] = cur;
          } else {
            const data = {};
            data[`column${cur.startColumn / 2}`] = cur;
            prev.push(data);
            prevLineNumber = cur.lineNumber;
          }
          return prev;
        }, []);
        return newItem;
      });
      console.log(result, 666);
      return result;
    },
  },
  filters: {
    formatStatus(val) {
      const statuss = ['禁用', '启用'];
      return statuss[val];
    },
    getNameOrValue(children, num, type) {
      if (!children) {
        return '';
      }
      const item = children.find((item) => item.startColumn == num);
      if (!item) {
        return '';
      }
      return type === 'name' ? item.name : item.value;
    },
  },
  async mounted() {
    // 获取url参数
    this.getQuery();
    // 数据
    // this.$api.ApiOperationalDocPageList({ page: 0, size: 1000 }).then((res) => {
    //   console.log(res);
    // });
    this.$api.ApiOperationalTemplateExport().then((res) => {
      this.templateData = this.tranform([{ name: '表头', value: '项目运营相关信息表' }, ...res.data]);
    });
    this.fetchUploadFile();
    this.getProjectList();
    // mock数据
    // this.tableData = this.result;
    // this.templateData = this.tranform([{ name: '表头', value: '项目运营相关信息表' }, ...this.result]);
    // console.log(this.templateData);
    this.fetchInfoExport();
    // this.$nextTick(() => {
    //   this.scrollItems = document.querySelectorAll('.scrollItem');
    //   this.$refs.scrollMenuRef.wrap.addEventListener('scroll', this.scrollFn, true);
    // });
  },
  beforeDestroy() {
    this.$refs.scrollMenuRef.wrap.removeEventListener('scroll', function () {});
  },
  methods: {
    parseTime: util.parseTime,
    getQueryVariable(variable) {
      var query = window.location.search.substring(1);
      if (!query) {
        query = window.location.hash.split('?')[1];
      }
      if (!query) {
        return;
      }
      var vars = query.split('&');
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        if (pair[0] == variable) {
          return decodeURIComponent(pair[1]);
        }
      }
      return '';
    },
    goback() {
      jDiwork.closeWin();
      jDiwork.openService('1743701729433092102');
    },
    getQuery() {
      this.form.id = this.getQueryVariable('id');
      this.form.orgCode = this.getQueryVariable('orgCode');
      this.form.orgName = this.getQueryVariable('orgName');
      this.form.projectCode = this.getQueryVariable('projectCode');
      this.form.projectName = this.getQueryVariable('projectName');
      this.form.fileId = this.getQueryVariable('fileId');
      this.form.fillMonth = this.getQueryVariable('fillMonth') || this.parseTime(new Date(), '{y}-{m}');
      this.form.fileName = this.getQueryVariable('fileName');
      this.isCheck = this.getQueryVariable('isCheck') || false;
    },
    activeCellMethod(item) {
      const { row, column } = item;
      const { _X_ROW_KEY, ...rest } = row;
      const keys = Object.keys(rest);
      const len = keys.length;
      return len % 2 === 0
        ? keys.indexOf(column.field) % 2 !== 0
        : column.field !== 'A' && keys.indexOf(column.field) % 2 === 0;
    },
    scrollFn() {
      console.log(1);
      return util.throttle(this.scrollMenu(this.scrollItems), 300);
    },
    scrollMenu(scrollItems) {
      return (e) => {
        console.log(e, 666);
        let i = 0;
        while (i < scrollItems.length) {
          if (scrollItems[i].offsetTop - e.target.scrollTop > 0) {
            break;
          }
          i++;
        }
        const id = scrollItems[i - 1]?.id;
        this.curIndex = id || 0;
      };
    },
    async sel(i) {
      this.curIndex = i;
      var anchor = document.getElementById(i);
      anchor.scrollIntoView({
        behavior: 'smooth',
        block: 'start',
      });
    },
    async fetchInfoExport() {
      if (this.form.id) {
        const { projectCode: projectId, fillMonth: month } = this.form;
        await this.$api
          .ApiOperationalInfoExport({ enabledFlag: true, page: 0, size: 1000, projectId, month })
          .then((res) => {
            try {
              this.tableData = res.data;
              this.curIndex = 0;
            } catch {
              this.tableData = [];
              this.curIndex = 0;
            }
          });
      }
    },
    async save() {
      const { projectCode: projectId, fillMonth: month } = this.form;
      this.tableData.forEach((item) => {
        item.projectRecordId = projectId;
        item.field = item.name;
        item.fieldValue = item.value;
        item.month = month;
        item.children?.forEach((it) => {
          it.projectRecordId = projectId;
          it.field = it.name;
          it.fieldValue = it.value;
          it.month = month;
        });
      });
      await this.$api.ApiOperationalInfoImport(this.tableData);
      await this.$api.ApiOperationalDocSaveOrUpdate(this.form).then((res) => {
        VXETable.modal.message({
          content: '保存成功',
          status: 'success',
        });
        setTimeout(() => {
          this.goback();
        }, 1000);
      });
    },
    handleRemove() {},
    tranform(tableData) {
      const table = tableData.map((item) => {
        if (!item.children || item.children.length === 0) {
          return item;
        } else {
          return item.children?.reduce((prev, cur) => {
            const last = prev[prev.length - 1];
            if (last?.lineNumber === cur.lineNumber) {
              last.children.push(cur);
            } else {
              prev.push({
                ...item,
                lineNumber: cur.lineNumber,
                children: [
                  {
                    ...cur,
                  },
                ],
              });
            }
            return prev;
          }, []);
        }
      });
      this.newTable = [];
      let start = 0;
      table.flat(1).forEach((item, i) => {
        if (item.name === '表头') {
          this.newTable.push({ A: item.value });
          this.mergeCells.push({
            row: 0,
            col: 0,
            rowspan: 1,
            colspan: 9,
          });
        } else {
          this.newTable.push({ A: item.name });

          if (this.newTable[start]['A'] !== item.name) {
            if (start !== 0) {
              this.mergeCells.push({
                row: start,
                col: 0,
                rowspan: i - start,
                colspan: 1,
              });
            }
            start = i;
          }
          this.mergeCells.push({
            row: start,
            col: 0,
            rowspan: i - start + 1,
            colspan: 1,
          });
          let last = this.newTable[this.newTable.length - 1];
          this.newTable[this.newTable.length - 1] = {
            ...last,
            ...item.children?.reduce((prev, cur) => {
              prev[this.atozArr[cur.startColumn - 1]] = cur.name;
              prev[this.atozArr[cur.startColumn]] = cur.value;
              // 合并列
              this.mergeCells.push({
                row: cur.lineNumber,
                col: cur.startColumn,
                rowspan: 1,
                colspan: cur.endColumn - cur.startColumn,
              });
              return prev;
            }, {}),
          };
        }
      });
      return table.flat(1);
    },
    //选择项目的操作
    openProject() {
      this.ProjectVisible = true;
    },
    closeProject3() {
      this.ProjectVisible = false;
    },
    //获取项目
    getProjectList() {
      const { userId } = JSON.parse(localStorage.getItem('userInfo'));
      this.$api.projectFetch({ userId: userId, ...this.ProjectParams }).then((res) => {
        this.ProjectData = res.data.list;
        this.Projectotal = res.data.totalPage;
        if (this.ProjectData && this.ProjectData.length > 0) {
          const { projectCode, projectName, orgCode, orgName } = this.ProjectData[0];
          this.form.projectName = this.form.projectName || projectName;
          this.form.projectCode = this.form.projectCode || projectCode;
          this.form.orgCode = this.form.orgCode || orgCode;
          this.form.orgName = this.form.orgName || orgName;
        }
      });
    },
    refreshPro() {
      this.ProjectParams.page = 1;
      this.ProjectParams.projectName = null;
      this.ProjectParams.projectId = null;
      this.getProjectList();
    },
    changePage(val) {
      this.ProjectParams.page = val;
      this.getProjectList();
    },
    rowClick(row) {
      row.flag = !row.flag;
      this.$refs['table'].$refs['table'].$refs['table'].toggleRowSelection(row, row.flag);
    },
    submitProject3() {
      if (this.projectList.length == 0) return this.$message.error('请选择项目');
      this.ProjectVisible = false;
      if (this.projectList.length > 0 && this.projectList[0] != undefined) {
        this.form.projectCode = this.projectList[0].projectCode;
        this.form.projectName = this.projectList[0].projectName;
        this.form.orgCode = this.projectList[0].orgCode;
        this.form.orgName = this.projectList[0].orgName;
      } else {
        this.form.projectCode = '';
        this.form.projectName = '';
        this.form.orgCode = '';
        this.form.orgName = '';
      }
    },
    sizeChange(val) {
      this.ProjectParams.pageSize = val;
      this.getProjectList();
    },
    searchProject(vname, vid) {
      // console.log(vname, vcode);
      this.ProjectParams.projectName = vname;
      // this.ProjectParams.projectCode = vcode;
      this.ProjectParams.projectId = vid;
      this.ProjectParams.page = 1;
      this.getProjectList();
    },
    handleSelect(e) {
      console.log(e, 'e');
      if (e.length > 1) {
        this.$refs['table'].$refs['table'].$refs['table'].clearSelection();
        this.$refs['table'].$refs['table'].$refs['table'].toggleRowSelection(e.pop());
      } else {
        if (e.length == 1) {
          this.projectList = [e.pop()];
        } else {
          this.projectList = [];
        }
      }
      console.log(this.projectList, 'this.selectProjectList');
    },
    async imp() {
      try {
        const workbook = new ExcelJS.Workbook();
        const { file } = await VXETable.readFile();
        const reader = new FileReader();
        // 获取上传文件名
        this.form.fileName = file.name;
        // 上传文件

        this.upload(file);
        //
        reader.readAsArrayBuffer(file);
        reader.onload = (event) => {
          var readerTarget = event.target;
          const buffer = readerTarget.result;
          workbook.xlsx.load(buffer).then((wb) => {
            var firstSheet = wb.worksheets[0];
            if (firstSheet) {
              var sheetValues = firstSheet.getSheetValues();
              const fieldIndex = 1;
              const records = sheetValues.slice(fieldIndex);
              this.templateData.forEach((item) => {
                item.children &&
                  item.children.forEach((it) => {
                    const value = records[it.lineNumber][it.startColumn + 1];
                    it.value =
                      value instanceof Date
                        ? this.parseTime(value, '{y}-{m}-{d}')
                        : typeof value === 'number'
                        ? value.toFixed(2)
                        : value;
                    it.groupName = item.name;
                  });
              });
              const table = this.templateData.reduce((prev, cur) => {
                if (prev.length === 0) {
                  prev.push({ ...cur });
                  return prev;
                }
                const last = prev[prev.length - 1];
                if (last.name === cur.name) {
                  last.children = [...last.children, ...cur.children];
                } else {
                  prev.push({ ...cur });
                }
                return prev;
              }, []);
              this.tableData = table.filter((item) => item.name !== '表头');
              this.newTable = this.tranform(table);
              this.curIndex = 0;
              VXETable.modal.message({
                content: '导入成功',
                status: 'success',
              });
            }
          });
        };
      } catch (e) {}
    },
    exp() {
      const workbook = new ExcelJS.Workbook();
      const sheet = workbook.addWorksheet('项目运营相关信息表', {
        properties: { defaultRowHeight: 30, defaultColWidth: 25 },
      });
      const atoi = this.atozArr;
      sheet.columns = atoi.map((key) => {
        return {
          header: key,
          key: key,
          width: '25',
        };
      });
      const fixedRow = 1;
      sheet.spliceRows(0, 1);
      this.templateData.forEach((item, i) => {
        if (item.name === '表头') {
          sheet.insertRow(1, this.newTable[i]);
        } else {
          sheet.insertRow(item.children ? item.children[0].lineNumber + fixedRow : null, this.newTable[i]);
        }
      });
      sheet.eachRow((row) => {
        row.alignment = { wrapText: true, vertical: 'middle', horizontal: 'center' };
        row._cells.forEach((item) => {
          item.border = {
            top: { style: 'thin', color: { argb: '000000' } },
            left: { style: 'thin', color: { argb: '000000' } },
            bottom: { style: 'thin', color: { argb: '000000' } },
            right: { style: 'thin', color: { argb: '000000' } },
          };
        });
        row.eachCell((cell) => {
          cell ? cell : {};
          cell.fill = {
            type: 'pattern',
            pattern: 'thin',
            fgColor: { argb: 'FF000000' },
            vertical: 'middle',
            horizontal: 'center',
          };
          //设置单元格样式
          // cell.fill = {
          //   type: 'gradient',
          //   gradient: 'angle',
          //   degree: 0,
          //   stops: [
          //     { position: 0, color: { argb: 'FF0000FF' } },
          //     { position: 1, color: { argb: 'FF0000FF' } },
          //   ],
          // };
          cell.font = {
            color: { argb: 'FF000000' },
            name: 'Calibri',
            family: 2,
            scheme: 'minor',
          };
          cell.alignment = { wrapText: true, vertical: 'middle', horizontal: 'center' };
        });
      });
      // 合并单元格
      const transformRow = (list) => {
        let start = 0;
        while (start < list.length) {
          const first = list[start];
          if (!first) {
            start++;
            continue;
          }
          const last = list.lastIndexOf(first);
          if (start !== last) {
            sheet.mergeCells(`A${start + fixedRow}:A${last + fixedRow}`);
          }
          start = last + 1;
        }
      };
      const transformColumn = (list) => {
        let start = 0;
        while (start < list.length) {
          if (list[start].name === '表头') {
            sheet.mergeCells('A1:I1');
            sheet.getCell(`A1`).alignment = { vertical: 'middle', horizontal: 'center' };
          } else {
            list[start].children &&
              list[start].children.forEach((it) => {
                const start = this.atozArr[it.startColumn];
                const end = this.atozArr[it.endColumn - 1];
                sheet.mergeCells(`${start}${it.lineNumber + fixedRow}:${end}${it.lineNumber + fixedRow}`);
                if (it.name.includes('日期') || it.name.includes('时间')) {
                  sheet.getCell(`${start}${it.lineNumber + fixedRow}`).dataValidation = {
                    type: 'date',
                    operator: 'lessThan',
                    showErrorMessage: true,
                    allowBlank: true,
                  };
                }
                // 添加下拉列表验证规则
                it.options &&
                  (sheet.getCell(`${start}${it.lineNumber + fixedRow}`).dataValidation = {
                    type: 'list',
                    allowBlank: true,
                    formulae: ['"' + it.options + '"'],
                  });
              });
          }
          start++;
        }
      };
      const AList = [];
      this.templateData.forEach((item) => {
        if (item.name !== '表头') {
          if (!item.children || item.children.length === 0) {
            AList[item.lineNumber] = item.name;
          } else {
            const child = item.children[0];
            AList[child.lineNumber] = item.name;
          }
        }
      });
      transformRow(AList);

      transformColumn(this.templateData);
      workbook.xlsx.writeBuffer().then((buffer) => {
        const blob = new Blob([buffer], { type: 'application/octet-stream' });
        // 导出 xlsx
        const linkElem = document.createElement('a');
        linkElem.target = '_blank';
        linkElem.download = `项目运营相关信息表.xlsx`;
        linkElem.href = URL.createObjectURL(blob);
        document.body.appendChild(linkElem);
        linkElem.click();
        document.body.removeChild(linkElem);
      });
    },
    upload(file) {
      let formData = new FormData();
      formData.append('file', file);
      // formData.append('businessId', this.form.id);
      const businessId = uuidv4();
      this.$api.ApiBipFileUpload(this.form.fileId || businessId, formData).then((res) => {
        if (res.code == 0) {
          // this.form.fileId = res.data.data[0];
          // this.fetchUploadFile();
          const fileObj = res.data.data ? res.data.data[0] : {};
          this.form.fileId = fileObj.objectId;
          this.fetchUploadFile();
        }
      });
    },
    async fetchUploadFile() {
      const { fileId: encryptionString } = this.form;
      if (!encryptionString) return;
      this.$api.ApiUploadGetFileByStringFetch({ encryptionString }).then((res) => {
        const obj = res.data.data ? res.data.data[0] : {};
        this.fileUrl = obj.filePath;
      });
    },
    download() {
      const linkElem = document.createElement('a');
      linkElem.target = '_blank';
      linkElem.download = this.form.fileName;
      linkElem.href = this.fileUrl;
      document.body.appendChild(linkElem);
      linkElem.click();
      document.body.removeChild(linkElem);
    },
  },
};
</script>
<style lang="scss" scoped>
.active {
  width: 56px;
  font-size: 14px;
  font-family: PingFang SC-Medium, PingFang SC;
  font-weight: 550 !important;
  color: #165dff !important;
  background-color: rgb(22, 93, 255, 0.03);
  cursor: pointer;
}
::v-deep {
  .normal {
    width: 340px !important;
  }
}
</style>
